package com.zsrd.system.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zsrd.auth.core.ResponseSupport;
import com.zsrd.auth.core.UserInfoUtil;
import com.zsrd.system.domain.SysMenu;
import com.zsrd.system.domain.SysRoleMenu;
import com.zsrd.system.domain.dto.UserMenu;
import com.zsrd.system.service.SysMenuService;

import com.zsrd.system.service.SysRoleMenuService;
import com.zsrd.user.domain.SysDept;
import com.zsrd.user.domain.SysUserRole;
import com.zsrd.user.service.SysUserRoleService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/menuManage")
public class MenuController {

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysUserRoleService sysUserRoleService;


    //
//    private List<SysMenu> getLeaf(List<SysMenu> sysAreaCodes, SysMenu item) {
//        //通过获取父id筛选出id判断是否相等
//        Stream<SysMenu> adminSysMenuStream = sysAreaCodes.stream()
//                .filter(items -> items.getParentMenuId() == (item.getMenuId()));
//        //如果相等就进入里面 将这条数据set进去
//        List<SysMenu> collect = adminSysMenuStream.map(adminSysMenu -> {
//            adminSysMenu.setItem(getLeaf(sysAreaCodes, adminSysMenu));
//            //然后返回 一直到没有了以后才返回一次list
//            return adminSysMenu;
//        }).collect(Collectors.toList());
//        return collect;
//    }
//
//    @RequestMapping(value = "/list", method = RequestMethod.GET)
//    public ResponseSupport getTree() {
//        // 获取当前用户信息
//        Map<String, Object> userinfo = UserInfoUtil.userinfo();
//        Object userId = userinfo.get("userId");
//        // 获取用户对应的权限
//        List<SysUserRole> sysUserRole = sysUserRoleService.getAll(userId);
//        ArrayList<SysRoleMenu> list2 = new ArrayList<>();
//        sysUserRoleService.getById((Serializable) userId);
//        for (SysUserRole userRole : sysUserRole) {
//            long roleId = userRole.getRoleId();
//            // 获取权限对应的菜单
//            SysRoleMenu byId = sysRoleMenuService.getById(roleId);
//            list2.add(byId);
//        }
//        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
//        for (SysRoleMenu menu : list2) {
//            // 获取用户信息的权限 和 表里的权限相等
//            wrapper.eq(SysRole::getRoleId, menu.getRoleId());
//        }
//
//        // 树形结构列表
//        //查寻所有数据
//        List<SysMenu> list = sysMenuService.list();
//        //首先筛选获取他的父id,并判断是否等于0  为啥等于0因为从零开始
//        Stream<SysMenu> adminSysMenuStream = list.stream().filter(item -> item.getParentMenuId() == 0);
//        //返回一个stream流方式通过.map方法将list里面的值赋值进去然后返回一个新的list集合
//        List<SysMenu> collect = adminSysMenuStream.map(adminSysMenu -> {
//            //将上面list查寻的数据调用下面递归的方法依次进行 从0开始 到结束 才退出返回一个新的list
//            adminSysMenu.setItem(getLeaf(list, adminSysMenu));
//            return adminSysMenu;
//        }).collect(Collectors.toList());
//        return ResponseSupport.success(collect);
//    }

    // 菜单列表
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ResponseSupport list() {
        //  获取当前用户信息
        Map<String, Object> userinfo = UserInfoUtil.userinfo();
        Object userId = userinfo.get("userId");
        // 获取用户对应的权限的菜单的所有信息
        List<UserMenu> sysMenus = sysUserRoleService.getRole(userId);
        if (sysMenus.size() == 0) {
            return ResponseSupport.fail("没有对应权限");
        }
        List<Tree<Long>> build = null;
        for (int i = 0; i < sysMenus.size(); i++) {
            UserMenu sysMenu = sysMenus.get(i);
            HashMap<Object, Object> meta = new HashMap<>();
            meta.put("icon", sysMenu.getIcon());
            long isFull = sysMenu.getIsFull();
            Boolean s = isFull == 0 ? false : true;
            meta.put("isFull", s);
            long isKeepAlive = sysMenu.getIsKeepAlive();
            Boolean ka = isKeepAlive == 0 ? false : true;
            meta.put("isKeepAlive", ka);
            long isFrame1 = sysMenu.getIsFrame();
            Boolean f = isFrame1 == 0 ? false : true;
            meta.put("isFrame", f);
            long isHide1 = sysMenu.getIsHide();
            Boolean h = isHide1 == 0 ? false : true;
            meta.put("isHide", h);
            String name = sysMenu.getMenuName();
            meta.put("title", name);
            sysMenu.setMeta(meta);
        }
        // 树形结构转换
        TreeNodeConfig config = new TreeNodeConfig();
        config.setIdKey("menuId");//默认为id可以不设置
        config.setParentIdKey("parentMenuId");//默认为parentId可以不设置
        config.setChildrenKey("children");

        build = TreeUtil.build(sysMenus, 0L, config, (object, tree) -> {
            tree.setId(object.getMenuId());
            tree.setParentId(object.getParentMenuId());
            tree.setName(object.getName());
            tree.putExtra("component", object.getComponent());
            tree.putExtra("path", object.getPath());
            tree.putExtra("meta", object.getMeta());
        });

        return ResponseSupport.success(build);
    }


    /**
     * 删除菜单
     *
     * @return 0代表存在 2 删除
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ApiOperation(value = "删除", notes = "删除")
    public ResponseSupport delete(@RequestBody SysMenu sysMenu) {
        sysMenu.setDelFlag(2);
        sysMenu.setUpdateTime(new Date());
        boolean b = sysMenuService.updateById(sysMenu);
        if (b == false) {
            return ResponseSupport.fail("删除失败");
        }
        return ResponseSupport.success(b);
    }

    /**
     * 新增菜单
     *
     * @param sysMenu
     * @return
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    @ApiOperation(value = "新增", notes = "新增")
    public ResponseSupport saveOrUpdate(@RequestBody SysMenu sysMenu) {
        // 如果menuId = 0 新增
        long menuId = sysMenu.getMenuId();
        String id = String.valueOf(menuId);
        if (StrUtil.equals(id, "0")) {
            // 新增
            sysMenu.setCreateTime(new Date());
            sysMenu.setUpdateTime(new Date());
            sysMenu.setDelFlag(0);
            sysMenuService.save(sysMenu);
            return ResponseSupport.success();
        } else {
            //修改
            sysMenu.setUpdateTime(new Date());
            boolean b = sysMenuService.updateById(sysMenu);
            if (b == false) {
                return ResponseSupport.fail("修改失败");
            }
            return ResponseSupport.success(b);
        }
    }

//
//    @RequestMapping(value = "update", method = RequestMethod.POST)
//    @ApiOperation(value = "修改", notes = "修改")
//    public ResponseSupport update(@RequestBody SysMenu sysMenu) {
//        sysMenu.setUpdateTime(new Date());
//        boolean b = sysMenuService.updateById(sysMenu);
//        if (b == false) {
//            return ResponseSupport.fail("修改失败");
//        }
//        return ResponseSupport.success(b);
//
//    }


    @RequestMapping(value = "/query", method = RequestMethod.POST)
    public ResponseSupport query() {
        List<SysMenu> sysMenus  = sysMenuService.list();
        if (CollectionUtil.isNotEmpty(sysMenus)) {
                // 树形结构转换
                TreeNodeConfig config = new TreeNodeConfig();
                config.setIdKey("menuId");//默认为id可以不设置
                config.setParentIdKey("parentMenuId");//默认为parentId可以不设置
                //config.setDeep(4);//最大递归深度
                //config.setWeightKey("priority");//排序字段

                List<Tree<Long>> build = TreeUtil.build(sysMenus, 0L, config, (object, tree) -> {
                    tree.setId(object.getMenuId());
                    tree.setParentId(object.getParentMenuId());
                    tree.setName(object.getName());
                    tree.putExtra("icon", object.getIcon());
                    tree.putExtra("menuName", object.getMenuName());
                    tree.putExtra("url", object.getPath());
                    tree.putExtra("component", object.getComponent());
                    tree.putExtra("orderNum", object.getOrderNum());


                });
                return ResponseSupport.success(build);
            }
            return ResponseSupport.fail("查询失败！");
        }
    }









